package app.modules.infrastructure.notification.facade;

import app.modules.infrastructure.notification.support.NotificationData;
import app.modules.infrastructure.notification.support.NotificationOption;
import app.modules.infrastructure.notification.support.NotificationProvider;
import app.modules.infrastructure.notification.support.NotificationResult;
import jasmine.framework.common.exception.ApplicationException;
import jasmine.framework.common.util.CheckUtil;
import jasmine.framework.context.RuntimeProvider;
import org.springframework.stereotype.Component;

import javax.annotation.Nullable;

/**
 * @author mh.z
 */
@Component
public class NotificationFacadeBean implements NotificationFacade {
    private RuntimeProvider runtimeProvider;
    private static final String NOTIFICATION_PROVIDER_NAME_SUFFIX = "NotificationProvider";

    public NotificationFacadeBean(RuntimeProvider runtimeProvider) {
        this.runtimeProvider = runtimeProvider;
    }

    @Override
    public NotificationResult sendNotification(String category, NotificationData data) {
        return sendNotification(category, data, null);
    }

    @Override
    public NotificationResult sendNotification(String category, NotificationData data,
                                               @Nullable NotificationOption option) {
        CheckUtil.notNull(category, "category null");

        String providerName = category + NOTIFICATION_PROVIDER_NAME_SUFFIX;
        NotificationProvider providerBean = runtimeProvider.getByName(providerName, false);

        if (providerBean == null) {
            throw new ApplicationException("not found NotificationProvider '" + providerName + "'", null);
        }

        NotificationResult result = providerBean.sendNotification(data, option);

        return result;
    }

}
